<template>
    <div class="reduce-container">
        {{ '122' }}
    </div>
</template>

<script setup>

/**
 * @des 手写一个reduce函数
*/

const arr = [1, 3, 4, 5, 6, 7, 8];

Array.prototype.myReduce = function (callback, initVal) {
    // 获取数组对象
    let arr = this
    // 定义preVal的初始值为initVal
    let preVal = initVal
    // 调用callback，次数同数组长度
    for (var i = 0; i < arr.length; i++) {
        let result = callback(preVal, arr[i])
        preVal = result
    }
    return preVal
}

const res = arr.myReduce((pre, item) => {
    return pre + item
}, 0);
console.log("♥ Hello ♥ ", res);

/**
 * @des 手写一个map函数
*/

const obj = [
    { name: "张三", id: '1' },
    { name: "张四", id: '2' },
    { name: "张五", id: '3' },
    { name: "张六", id: '4' },
]

Array.prototype.myMap = function (callback) {
    let arr = this;
    let result = []
    for (let i = 0; i < arr.length; i++) {
        result.push(callback(arr[i]));
    }
    return result;
}
const resMap = obj.myMap(item => item.id)

console.log("♥ H ♥ ", resMap);


</script>

<style lang="scss" scoped></style>